package cn.ihoway.socket;

import cn.ihoway.game.Division;
import cn.ihoway.util.HowayLog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.UUID;

@Component
public class GameWebSocketHandler extends TextWebSocketHandler {

    private final HowayLog logger = new HowayLog(GameWebSocketHandler.class);

    /**
     * socket 建立成功事件
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Object sessionId = session.getAttributes().get("session_id");
        if (sessionId != null) {
            logger.info("用户" + sessionId + "登录成功");
            GameSessionManager.add(sessionId.toString(), session);
        }
    }

    /**
     * 接收消息事件
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 获得客户端传来的消息
        String payload = message.getPayload();
        JSONObject req = JSON.parseObject(payload);
        Division division = new Division();
        division.doExecute(req,session);
    }

    /**
     * socket 断开连接时
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Object sessionId = session.getAttributes().get("session_id");
        if (sessionId != null) {
            GameSessionManager.remove(sessionId.toString());
            logger.info( sessionId + " 退出 , status = " + status);
            Division.exit(sessionId.toString());
        }
    }

    /**json格式？
     * 解析客户端获取到的消息
     * 创建房间请求：$CREATE$
     * 加入房间(1001)请求：$JOIN$ 1001
     * 发言请求：$CHAT$ content
     * 退出房间请求：$EXIT$
     * 投票请求：$VOTE$
     * 杀死玩家请求：$KILL$ player_id
     * 获取一个情报：$GET$
     */
    private void parseMessage(){

    }

    /**
     * 服务端返回响应 json格式
     * 房间id [ROOM] id
     * 身份 [IDENTITY] player_id character信息 是否卧底
     * 游戏是否结束
     * 返回一个情报信息
     *
     */



}